//
//  HEInputViewPluginVideo.m
//  HealthFamily
//
//  Created by 吴欧 on 2021/2/18.
//  Copyright © 2021 honglutec. All rights reserved.
//

#import "HEInputViewPluginVideo.h"
#import "HXPhotoPicker.h"
#import "HEIMVideoObject.h"

@interface HEInputViewPluginVideo ()

@property (nonatomic, copy) LCCKIdResultBlock sendCustomMessageHandler;
@property(nonatomic,strong) HXPhotoManager *videoManage;
// 创建一个全局的group
@property (nonatomic, strong) dispatch_group_t group;

@end

@implementation HEInputViewPluginVideo
@synthesize inputViewRef = _inputViewRef;
@synthesize sendCustomMessageHandler = _sendCustomMessageHandler;

#pragma mark -
#pragma mark - LCCKInputViewPluginSubclassing Method

+ (LCCKInputViewPluginType)classPluginType {
    return LCCKInputViewPluginTypeShortVideo;
}

#pragma mark -
#pragma mark - LCCKInputViewPluginDelegate Method

/*!
 * 插件图标
 */
- (UIImage *)pluginIconImage {
    return IMAGE_NAMED(@"inp_video");
//    return [self imageInBundlePathForImageName:@"add_report"];
}

/*!
 * 插件名称
 */
- (NSString *)pluginTitle {
    return @"视频";
}

/*!
 * 插件对应的 view，会被加载到 inputView 上
 */
- (UIView *)pluginContentView {
    return nil;
}

- (void)pluginDidClicked {
    [super pluginDidClicked];

    [self selectVideoHandler];
}

- (void)selectVideoHandler {
    [self.videoManage clearSelectedList];

    KWeakSelf
    HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithManager:self.videoManage doneBlock:^(NSArray<HXPhotoModel *> * _Nullable allList, NSArray<HXPhotoModel *> * _Nullable photoList, NSArray<HXPhotoModel *> * _Nullable videoList, BOOL original, UIViewController * _Nullable viewController, HXPhotoManager * _Nullable manager) {
        
        NSMutableArray *arr = @[].mutableCopy;

        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            weakSelf.group = dispatch_group_create();

            for (HXPhotoModel *item in videoList) {
                dispatch_group_enter(weakSelf.group);

                [item getAssetURLWithSuccess:^(NSURL * _Nullable URL, HXPhotoModelMediaSubType mediaType, BOOL isNetwork, HXPhotoModel * _Nullable model) {
                    HEIMVideoObject *video = [[HEIMVideoObject alloc] init];
                    video.url = URL;
                    video.sourceType = HEIMMediaSourceTypeNative;
                    [arr addObject: video];
                    dispatch_group_leave(weakSelf.group);

                } failed:^(NSDictionary * _Nullable info, HXPhotoModel * _Nullable model) {
                    dispatch_group_leave(weakSelf.group);
                }];
            }

            //因上面请求中有加入dispatch_group_enter 和 dispatch_group_leave,所以真正等待上面线程执行完才执行这里面的请求
            dispatch_group_notify(self.group, queue, ^{
                
                for (HEIMVideoObject *video in arr) {
                    HEIMMessage *message = [[HEIMMessage alloc] init];
                    message.type = HEIMMessageTypeVideo;
                    message.messageObject = video;
                    message.from = weakSelf.inputViewRef.userInfo.id;
                    message.actor = HEActorTypeUser;
                    message.to = weakSelf.inputViewRef.session.sessionId;
                    HEIMMessageModel *model = [[HEIMMessageModel alloc] initWithMessage: message];
                    model.deliveryState = HEIMMessageDeliveryStateDelivering;

                    if ([weakSelf.inputViewRef.delegate respondsToSelector:@selector(sendMessage:)]) {
                        [weakSelf.inputViewRef.delegate sendMessage: model];
                    }
                }
            });
        });
    } cancelBlock:^(UIViewController * _Nullable viewController, HXPhotoManager * _Nullable manager) {
        
    }];
    
    [self.conversationViewController presentViewController:nav animated:YES completion:nil];
}


/**
 前往相机
 */
- (void)goCameraViewController {
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [[self hx_viewController].view hx_showImageHUDText:[NSBundle hx_localizedStringForKey:@"无法使用相机!"]];
        return;
    }
    HXWeakSelf
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (granted) {
                if (weakSelf.videoManage.configuration.replaceCameraViewController) {
                    HXPhotoConfigurationCameraType cameraType;
                    if (weakSelf.videoManage.type == HXPhotoManagerSelectedTypePhoto) {
                        cameraType = HXPhotoConfigurationCameraTypePhoto;
                    }else if (weakSelf.videoManage.type == HXPhotoManagerSelectedTypeVideo) {
                        cameraType = HXPhotoConfigurationCameraTypeVideo;
                    }else {
                        if (!weakSelf.videoManage.configuration.selectTogether) {
                            if (weakSelf.videoManage.afterSelectedPhotoArray.count > 0) {
                                cameraType = HXPhotoConfigurationCameraTypePhoto;
                            }else if (weakSelf.videoManage.afterSelectedVideoArray.count > 0) {
                                cameraType = HXPhotoConfigurationCameraTypeVideo;
                            }else {
                                cameraType = HXPhotoConfigurationCameraTypePhotoAndVideo;
                            }
                        }else {
                            cameraType = HXPhotoConfigurationCameraTypePhotoAndVideo;
                        }
                    }
                    switch (weakSelf.videoManage.configuration.customCameraType) {
                        case HXPhotoCustomCameraTypePhoto:
                            cameraType = HXPhotoConfigurationCameraTypePhoto;
                            break;
                        case HXPhotoCustomCameraTypeVideo:
                            cameraType = HXPhotoConfigurationCameraTypeVideo;
                            break;
                        case HXPhotoCustomCameraTypePhotoAndVideo:
                            cameraType = HXPhotoConfigurationCameraTypePhotoAndVideo;
                            break;
                        default:
                            break;
                    }
                    if (weakSelf.videoManage.configuration.shouldUseCamera) {
                        weakSelf.videoManage.configuration.shouldUseCamera([weakSelf hx_viewController], cameraType, weakSelf.videoManage);
                    }
                    weakSelf.videoManage.configuration.useCameraComplete = ^(HXPhotoModel *model) {
                        [weakSelf customCameraViewController:nil didDone:model];
                    };
                    return;
                }
                HXCustomCameraViewController *vc = [[HXCustomCameraViewController alloc] init];
                vc.delegate = weakSelf;
                vc.manager = weakSelf.videoManage;
                vc.isOutside = YES;
                HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithRootViewController:vc];
                nav.isCamera = YES;
                nav.supportRotation = weakSelf.videoManage.configuration.supportRotation;
                nav.modalPresentationStyle = UIModalPresentationOverFullScreen;
                nav.modalPresentationCapturesStatusBarAppearance = YES;
                [[weakSelf hx_viewController] presentViewController:nav animated:YES completion:nil];
            }else {
                [HXPhotoTools showUnusableCameraAlert:weakSelf.hx_viewController];
            }
        });
    }];
}

- (void)customCameraViewController:(HXCustomCameraViewController *)viewController didDone:(HXPhotoModel *)model {
    [self cameraDidNextClick:model];
}
/**
 相机拍完之后的代理

 @param model 照片模型
 */
- (void)cameraDidNextClick:(HXPhotoModel *)model {
    
}


#pragma mark -
#pragma mark - Private Methods


#pragma mark - laz
- (HXPhotoManager *)videoManage {
    if (!_videoManage) {
        _videoManage = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypeVideo];
        _videoManage.configuration.type = HXConfigurationTypeWXMoment;
        _videoManage.configuration.openCamera = YES;
        _videoManage.configuration.photoMaxNum = 0;
        _videoManage.configuration.videoMaxNum = 9;
        _videoManage.configuration.maxNum = 9;
        _videoManage.configuration.lookLivePhoto = YES;
        _videoManage.configuration.selectTogether = NO;
        _videoManage.configuration.deleteTemporaryPhoto = YES;
        _videoManage.configuration.creationDateSort = YES;
        
        _videoManage.configuration.videoMaximumSelectDuration = 60 * 10;
    }
    return _videoManage;
}

@end
